<?php

namespace app\api\controller;

use app\admin\model\VCourse;
use app\admin\model\VLesson;
use app\admin\model\VUserOrder;
use app\common\controller\Api;
use app\common\logic\ShareWechatLogic;
use app\common\logic\VodLogic;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedRight = ['*'];

    /**
     * 首页
     */
    public function index()
    {
        $v_banner_db = Db::name("v_banner");
        $banner = $v_banner_db->where('state=1')->field("image,url")
            ->order("sort desc")->select();

        $v_voice_db = Db::name('v_course');
        $voice_list = $v_voice_db->alias('v')
            ->join('fa_v_teacher t', 't.id=v.v_teacher_id', 'left')
            ->where('media_type=2')
            ->field("v.id,v.cover_image,v.title,v.count,v.price,v.refer_price,v.is_publish,t.name teacher_name")
            ->limit(2)
            ->order('sort desc')->select();

        $video_list = $v_voice_db->alias('v')
            ->join('fa_v_teacher t', 't.id=v.v_teacher_id', 'left')
            ->where('media_type=1')
            ->field("v.id,v.cover_image,v.title,v.count,v.price,v.refer_price,v.is_publish,t.name teacher_name")
            ->limit(2)
            ->order('sort desc')->select();

        $list = [
            'banner' => $banner,
            'voice' => $voice_list,
            'video' => $video_list,
        ];
        $this->success('success', $list);
    }

    /**
     * 获取视频列表
     */
    function get_video_list()
    {
        $v_voice_db = Db::name('v_course');
        $list = $v_voice_db->alias('v')
            ->join('fa_v_teacher t', 't.id=v.v_teacher_id', 'left')
            ->where('v.media_type=1')
            ->field("v.id,v.cover_image,v.title,v.count,v.price,v.refer_price,v.is_publish,t.name teacher_name")
            ->order('v.is_publish desc,sort desc')->select();

        $this->success('success', $list);
    }

    /**
     * 获取音频列表
     */
    function get_voice_list()
    {
        $v_voice_db = Db::name('v_course');
        $list = $v_voice_db->alias('v')
            ->join('fa_v_teacher t', 't.id=v.v_teacher_id', 'left')
            ->where('v.media_type=2')
            ->field("v.id,v.cover_image,v.title,v.count,v.price,v.refer_price,v.is_publish,t.name teacher_name")
            ->order('v.is_publish desc,sort desc')->select();

        $this->success('success', $list);
    }

    /**
     * 课程介绍
     */
    public function video_introduce()
    {
        $course_id = input('course_id');
        if (!$course_id) {
            $this->error('课程ID获取失败');
        }
        $v_course_db = Db::name('v_course');
        $field = "a.id,a.title,a.count,a.desc,a.v_teacher_id,b.avatar,b.content,b.name,b.sex,a.price,a.refer_price,a.media_type";
        $info = $v_course_db->alias('a')
            ->join('fa_v_teacher b', 'b.id=a.v_teacher_id', 'left')
            ->where(['a.id' => $course_id])
            ->field($field)
            ->find();
        if ($info) {
            $user_order_db = Db::name("v_user_order");
            $order = $user_order_db->where("user_id", $this->user_id)
                ->where("v_course_id", $course_id)
                ->where("state=1")->find();
            $info['is_buy'] = $order ? 1 : 0;

            $this->success('课程介绍获取成功', $info);
        } else {
            $this->error('课程介绍获取失败');
        }
    }

    /**
     * 课程目录
     */
    function video_directory()
    {
        $course_id = input('course_id');
        if (!$course_id) {
            $this->error('课程ID获取失败');
        }
        $v_lesson_db = Db::name('v_lesson');
        $result = $v_lesson_db->where(['v_course_id' => $course_id])
            ->order('sort asc')
            ->field("id,v_video_id,title,is_free")->select();
        $video_ids = array_column($result, 'v_video_id');

        $video_db = Db::name('v_video');
        $video_list = $video_db->where("id", 'in', $video_ids)->column('duration', 'id');
        foreach ($result as $k => &$v) {
            $v['duration'] = isset($video_list[$v['v_video_id']]) ? format_time($video_list[$v['v_video_id']]) : "00:00";
        }

        $current = 0;
        $user_play_log_db = Db::name("v_user_play_log");
        $play_log = $user_play_log_db->where('user_id', $this->user_id)
            ->where('v_course_id', $course_id)
            ->order('id desc')->find();
        if ($play_log) {
            $current = $play_log['v_lesson_id'];
        }

        if ($current < 1) {
            $lesson_db = Db::name('v_lesson');
            $lesson = $lesson_db->where('v_course_id', $course_id)->where('is_free=1')->order("sort asc")->find();
            if ($lesson) {
                $current = $lesson['id'];
            }   
        }

        if ($result) {
            $this->success('课程章节获取成功', [
                'list' => $result,
                'current' => $current,
            ]);
        } else {
            $this->error('课程章节获取失败');
        }
    }

    /**
     * 获取问题集
     */
    function get_faq()
    {
        $faq_db = Db::name('v_faq');
        $list = $faq_db->order('sort desc')->field("ask,content")->select();
        $this->success('success', $list);
    }

    /**
     * 获取评论
     */
    function get_comment()
    {
        $course_id = input('course_id');
        $curr_page = input('page', 1);
        $size = input('size', 20);

        if ($course_id < 1) $this->error("课程id不能为空");
        $user_comment_db = Db::name('v_user_comment');
        $count = $user_comment_db->where('v_course_id', $course_id)
            ->where('is_check', 1)->count();

        $list = $user_comment_db->where('v_course_id', $course_id)
            ->where('is_check', 1)
            ->limit($size * ($curr_page - 1), $size)
            ->field('id,content,user_id,createtime')
            ->order('id desc')->select();

        $user_db = Db::name("user");
        $uids = array_column($list, 'user_id');
        $users = $user_db->where("id", 'in', $uids)->column("nickname,avatar", 'id');

        foreach ($list as $k => $v) {
            $list[$k]['createtime'] = date("Y-m-d", $v['createtime']);
            $list[$k]['is_del'] = $this->user_id == $v['user_id'] ? 1 : 0;
            $list[$k]['nickname'] = isset($users[$v['user_id']]) ? $users[$v['user_id']]['nickname'] : "";
            $list[$k]['avatar'] = isset($users[$v['user_id']]) ? $users[$v['user_id']]['avatar'] : "";
        }
        $this->success('success', [
            'list' => $list,
            'count' => $count,
        ]);
    }

    /**
     *获取凭证
     */
    public function get_playAuth()
    {
        $course_id = input('course_id');
        if ($course_id < 1) {
            $this->error('课程id不能为空');
        }

        $lesson_id = input('lesson_id');
        $v_lesson_db = Db::name('v_lesson');

        $user_play_log_db = Db::name("v_user_play_log");
        if ($lesson_id > 0) {
            $lesson = $v_lesson_db->where(['v_course_id' => $course_id, 'id' => $lesson_id])->find();
        } else {
            $lesson_id = $user_play_log_db->where('v_course_id', $course_id)
                ->where('user_id', $this->user_id)->order('createtime desc')
                ->value('v_lesson_id');
            if ($lesson_id > 0) {
                $lesson = $v_lesson_db->where(['v_course_id' => $course_id, 'id' => $lesson_id])->find();
            } else {
                $lesson = $v_lesson_db->where(['v_course_id' => $course_id])->order('sort asc')->find();
                $lesson_id = $lesson['id'];
            }
        }

        if (empty($lesson)) $this->error("章节不存在");

        $course_db = Db::name('v_course');
        $video_db = Db::name('v_video');
        $user_order_db = Db::name("v_user_order");
        $order = $user_order_db->where('v_course_id', $course_id)->where("user_id", $this->user_id)->find();
        if (empty($order) && $lesson['is_free'] == 0) $this->error("没有免费章节，请购买后观看");

        $video = $video_db->where(['id' => $lesson['v_video_id']])->find();
        $media_type = $course_db->where('id', $lesson['v_course_id'])->value('media_type');
        if (!$video) {
            $this->error('视频数据获取失败');
        }

        $user_play_log_db->insert([
            'user_id' => $this->user_id,
            'v_course_id' => $course_id,
            'v_lesson_id' => $lesson_id,
            'createtime' => time(),
        ]);

        if ($media_type == 1) {
            $this->get_auth($video['video_id'], $video['cover_image'], $lesson_id);
        } else {
            $this->get_video_info($video['video_id'], $video['cover_image'], $lesson_id, $video['mad_content']);
        }
    }

    /**
     * 获取视频的播放信息
     * @param $video_id
     * @param $img
     * @param $lesson_id
     * @return array
     */
    protected function get_video_info($video_id, $img, $lesson_id, $mad)
    {
        $playVideo = VodLogic::get_play_info($video_id, $img, $lesson_id);
        if (!isset($playVideo->PlayInfoList->PlayInfo[1]->PlayURL)) {
            $this->error('获取失败');
        }

        $this->success('success', [
            'PlayURL' => isset($playVideo->PlayInfoList->PlayInfo[1]->PlayURL) ? $playVideo->PlayInfoList->PlayInfo[1]->PlayURL : '',
            'videoId' => $video_id,
            'img' => $img,
            'lessonId' => $lesson_id,
            'mad' => $mad,
        ]);
    }

    /**
     * @param $video_id
     * @param $img
     */
    protected function get_auth($video_id, $img, $lesson_id)
    {
        $playAuthResponse = VodLogic::get_video_playAuth($video_id);
        if (!isset($playAuthResponse->PlayAuth)) {
            $this->error('获取失败');
        }

        $this->success('success', [
            'UploadAuth' => isset($playAuthResponse->PlayAuth) ? $playAuthResponse->PlayAuth : '',
            'videoId' => $video_id,
            'lessonId' => $lesson_id,
            'img' => $img,
        ]);
    }

    /**
     * 获取下一个音频信息
     */
    function get_next()
    {
        $type = input('type', 0);
        $lesson_id = input('lesson_id');
        if ($lesson_id < 0) {
            $this->error('课程id获取失败');
        };

        $lesson = VLesson::where('id', $lesson_id)->field('id,v_course_id,sort')->find();
        if (!$lesson) {
            $this->error('课程信息获取失败');
        }

        $where = [];
        if ($type == 0) {
            $where['sort'] = ['lt', $lesson['sort']];
            $sort = "sort desc";
        } else {
            $where['sort'] = ['gt', $lesson['sort']];
            $sort = "sort asc";
        }
        $r_lesson_id = VLesson::where([
            'v_course_id' => $lesson['v_course_id'],
        ])->where($where)->order($sort)
            ->value('id');
        if ($r_lesson_id < 1) {
            if ($type == 0) $this->error("没有上一首了");

            $this->error("没有下一首了");
        }

        $next_lesson = VLesson::alias('l')
            ->join('fa_v_video v', 'v.id = l.v_video_id', 'left')
            ->where([
                'l.id' => $r_lesson_id,
            ])->field('l.id,v.video_id,l.v_course_id,l.is_free,v.cover_image,v.mad_content')->find();
        if (empty($next_lesson)) {
            $this->error('多媒体数据获取失败');
        };
        $media_type = VCourse::where('id', $next_lesson['v_course_id'])->value('media_type');
        if ($next_lesson['is_free'] == 1) {
            if ($media_type == 1) {
                $this->get_auth($next_lesson['video_id'], $next_lesson['cover_image'], $next_lesson['id']);
            } else {
                $this->get_video_info($next_lesson['video_id'], $next_lesson['cover_image'], $next_lesson['id'], $next_lesson['mad_content']);
            }
        }

        $exist_id = VUserOrder::where([
            'v_course_id' => $next_lesson['v_course_id'],
            'user_id' => $this->user_id,
            'state' => 1,
        ])->value('id');
        if (!$exist_id) {
            $this->error('请先订购此课程');
        }

        if ($media_type == 1) {
            $this->get_auth($next_lesson['video_id'], $next_lesson['cover_image'], $next_lesson['id']);
        } else {
            $this->get_video_info($next_lesson['video_id'], $next_lesson['cover_image'], $next_lesson['id'], $next_lesson['mad_content']);
        }
    }

    function share_page()
    {
        $course_id = input('course_id');
        $title = '';
        $desc = "";
        $image = "";
        if ($course_id > 0) {
            $course_db = Db::name("v_course");
            $course = $course_db->where('id', $course_id)->field("")->find();
            if ($course) {
                $title = $course['title'];
                $desc = $course['desc'];
                $image = config("site.cdnurl") . $course['cover_image'];
            }
        }

        if (empty($title)) {
            $teacher_db = Db::name('v_teacher');
            $teacher = $teacher_db->find();
            if ($teacher) {
                $title = $teacher['name'];
                $desc = $teacher['content'];
                $image = config("site.cdnurl") . $teacher['avatar'];
            }

        }
        $url = input('url');
        $package = ShareWechatLogic::getSignedPackage($url);

        $package['title'] = $title;
        $package['desc'] = $desc;
        $package['image'] = $image;
//        log_print($package, $url);
        $this->success("请求成功", "", $package);
    }

    function search()
    {
        $keyword = input('search');
        if (!empty($keyword)) {
            $list = VCourse::where("title", 'like', '%' . $keyword . '%')
                ->where('is_publish', 1)
                ->field('id,cover_image,title,count,price,refer_price,media_type')->select();
        } else {
            $list = VCourse::where('is_publish', 1)
                ->field('id,cover_image,title,count,price,refer_price,media_type')->select();
        }


        $this->success('success', $list);
    }

    /*
     * 新通知条数
     */
    public function get_message_num()
    {
        $num = Db::name('user')->where('id',$this->user_id)->value('msg');
        if($num){
            $this->success('success', $num);
        }else{
            $this->success('success', 0);
        }
    }

    /*
     * 消息列表
     */

    public function message_list()
    {
        $curr_page = input('page', 1);
        $size = input('size', 20);
        $message = Db::name('v_user_message');
        $list = $message
            ->limit($size * ($curr_page - 1), $size)
            ->order('id desc')->select();
        $count = $message
            ->count();
        foreach ($list as $k => $v) {
            $list[$k]['createtime'] = date("Y-m-d H:i:s", $v['createtime']);
        }
        Db::name('user')->where('id',$this->user_id)->update(array('msg'=>0));
        $this->success('success', [
            'list' => $list,
            'count' => $count,
        ]);

    }




}



